package test.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import test.couchdb.ModelsDb;

import com.n1global.acc.util.UrlBuilder;
import com.ning.http.util.Base64;

@Controller
@RequestMapping("/attachment/{docId}")
public class AttachmentController {
    @Autowired
    private ModelsDb modelsDb;

    @RequestMapping(method = RequestMethod.GET)
    public void getAttachment(@PathVariable String docId, String name, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String url = new UrlBuilder(modelsDb.getDbUrl()).addPathSegment(docId).addPathSegment(name).build();

        HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();

        String encoded = Base64.encode((modelsDb.getConfig().getUser() + ":" + modelsDb.getConfig().getPassword()).getBytes(StandardCharsets.UTF_8));

        urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
        urlConnection.setRequestProperty("Connection", "close");

        try {
            Enumeration<String> e = request.getHeaderNames();

            while (e.hasMoreElements()) {
                String headerName = e.nextElement();

                urlConnection.addRequestProperty(headerName, request.getHeader(headerName));
            }

            for (Entry<String, List<String>> entry : urlConnection.getHeaderFields().entrySet()) {
                for (String value : entry.getValue()) {
                    response.addHeader(entry.getKey(), value);
                }
            }

            response.setStatus(urlConnection.getResponseCode());

            try (InputStream in = urlConnection.getInputStream()) {
                StreamUtils.copy(in, response.getOutputStream());
            }
        } finally {
            urlConnection.disconnect();
        }
    }
}
